#!/usr/bin/env python

import sys
import monitor
import urllib2
import urllib
import pprint
import math

def main(args):

    source_url = args[0]
    
    NAME=0
    PASSED=1
    NOT_RUN = 2
    FAILED = 3
    # http://chart.apis.google.com/chart?cht=bvs&chs=200x125&chd=t:10,50,60,80,40|50,60,100,40,20&chco=4d89f9,c6d9fd&chbh=20&chds=0,160

    url = 'http://chart.apis.google.com/chart'
    url = 'http://chart.apis.google.com/chart?cht=bvs&chbh=a&chs=1000x300&chd=t:'

    data = {
        'cht': 'lc',
        'chbh': 'a',
        'chs': '1000x300',
        'chxt': 'y,x,r,y,x',
        'chm': 'v,00FF00,0,::1,1|v,FFFF00,1,::1,1|D,FF0000,2,3,1',
#        'chxl': '2:|hippo',

#        'chof': 'validate',
        'chxp': '3,50|4,50',
        'chxs': '2,FF0000',
        'chdl': 'RUN|IGNORED|% IGNORED',
        'chco': '00FF00,FFFF00,FF0000',
        }
    

    
    results = monitor.load_results(source_url)
    for k in results.keys():
        if results[k][NAME] < 1000:
            del results[k]
    keys = results.keys()
    keys.sort()

    highest = int(max(results[key][PASSED] + results[key][NOT_RUN] for key in keys))
    lowest = int(min(results[key][PASSED] for key in keys))

    lowest = 0
    diff = highest-lowest
    #highest += int(0.1*diff)
    #lowest -= int(0.1*diff)

    print [results[key][PASSED] for key in keys]
    data['chd'] = ('t2:' +
                   ','.join([str(results[key][NOT_RUN] + results[key][PASSED] - lowest) for key in keys]) +
                   '|' +
                   ','.join([str(results[key][NOT_RUN]-lowest) for key in keys]) + 
                   '|' +
                   ','.join([str(highest*(1.0*results[key][NOT_RUN]/(max(1,results[key][PASSED] + results[key][NOT_RUN])))) for key in keys])
                   )

    data['chds'] = '0,' + str(highest-lowest) 
    data['chxr'] = '0,' + str(lowest) + ',' + str(highest) + '|2,0,100'

    chxl = '3:|# Tests|4:|build number|1:|'
    for i in range(len(keys)):
        if not i % 10:
            chxl += str(results[keys[i]][NAME])
        chxl += '|'
    data['chxl'] = chxl

    pprint.pprint(data)

    f = file('chart.png', 'wb')
    f.write(urllib2.urlopen(url, urllib.urlencode(data)).read())
    f.close()
    return 0


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

